package com.ten.service;

import com.ten.common.core.entity.AclPermission;
import com.ten.common.core.entity.AclUser;
import com.ten.feign.SystemFeign;
import com.ten.common.core.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：Q大侠
 * @date ：Created in 2022/12/1 18:59
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class MyUserService implements UserDetailsService {

    @Autowired
    private SystemFeign systemFeign;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户查询用户信息
        Result<AclUser> result = systemFeign.getByName(s);
        if (result!=null && result.getData()!=null){
            AclUser aclUser = result.getData();
            Result<List<AclPermission>> result1 = systemFeign.getByUserid(aclUser.getId());
            if (result1!=null){
                List<AclPermission> permissions =  result1.getData();
                List<SimpleGrantedAuthority> authorities = permissions.stream()
                                                                      //过滤掉不满足条件的元素
                                                                      .filter(item->item.getPermissionValue()!=null&&item.getPermissionValue()!="")
                                                                      //把集合中的元素类型转换为SimpleGrantedAuthority类型
                                                                      .map(item->new SimpleGrantedAuthority(item.getPermissionValue()))
                                                                      .collect(Collectors.toList());
                return new User(aclUser.getUsername(), aclUser.getPassword(), authorities);
            }

        }
        return null;
    }
}
